<template>
  <FormTree
    :modelValue="modelValue"
    :tree="permissionConfigTree"
    showCheckbox
    defaultExpandAll
    @update:model-value="onInput"
  />
</template>
<script lang="ts" setup>
import { routes } from "@/router";
import type { PermissionKeyEnum } from "@/utils";
import { generateRouteMetaRawTree } from "@/utils";
import type { FormTreeItem } from "@/components/form";
import { FormTree } from "@/components/form";

const props = defineProps<{
  modelValue: PermissionKeyEnum[];
  /** 检测是否禁用 */
  checkDisabled?: (item: string | number) => boolean;
  /**
   * 是否过滤不可用项
   * !!! 如果不是末端选项 可能会导致子节点过滤
   */
  filterDisabled?: boolean;
}>();
const emits =
  defineEmits<(e: "update:modelValue", value: PermissionKeyEnum[]) => void>();

// 生成权配置限树
const permissionConfigTree: FormTreeItem[] = generateRouteMetaRawTree<any>(
  routes,
  {
    // 只显示配置权限了的 或者 有子节点的（子节点配置了权限）
    filterFn: (raw, haveChildren) =>
      (raw.checkPermission || haveChildren) &&
      (props.filterDisabled
        ? props.checkDisabled?.(raw.permissionKey!) !== true
        : true),
    sortFn: (a, b) => a.extra!.menuSort - b.extra!.menuSort,
    mapFn: (item) => {
      const id = item.permissionKey || item.path;
      const res: FormTreeItem = {
        id,
        label: item.title,
        children: item.children,
        disabled: props.checkDisabled?.(id) || false,
        extra: item,
      };
      return res;
    },
  },
);

const onInput = (value: (string | number)[]) => {
  emits("update:modelValue", value as PermissionKeyEnum[]);
};
</script>
